package 每日一题;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 面试题 16.20. T9键盘
 * 在老式手机上，用户通过数字键盘输入，手机将提供与这些数字相匹配的单词列表。每个数字映射到0至4个字母。给定一个数字序列，实现一个算法来返回匹配单词的列表。你会得到一张含有有效单词的列表。映射如下图所示：
 *
 *
 *
 * 示例 1:
 *
 * 输入: num = "8733", words = ["tree", "used"]
 * 输出: ["tree", "used"]
 * 示例 2:
 *
 * 输入: num = "2", words = ["a", "b", "c", "d"]
 * 输出: ["a", "b", "c"]
 * 提示：
 *
 * num.length <= 1000
 * words.length <= 500
 * words[i].length == num.length
 * num中不会出现 0, 1 这两个数字
 */
public class D220715_T16_20 {
    //将单词转为 按键数字
    public List<String> getValidT9Words(String num, String[] words) {
        HashMap<Character, String> keys = new HashMap<>();
        keys.put('a', "2");
        keys.put('b', "2");
        keys.put('c', "2");
        keys.put('d', "3");
        keys.put('e', "3");
        keys.put('f', "3");
        keys.put('g', "4");
        keys.put('h', "4");
        keys.put('i', "4");
        keys.put('j', "5");
        keys.put('k', "5");
        keys.put('l', "5");
        keys.put('m', "6");
        keys.put('n', "6");
        keys.put('o', "6");
        keys.put('p', "7");
        keys.put('q', "7");
        keys.put('r', "7");
        keys.put('s', "7");
        keys.put('t', "8");
        keys.put('u', "8");
        keys.put('v', "8");
        keys.put('w', "9");
        keys.put('x', "9");
        keys.put('y', "9");
        keys.put('z', "9");

        ArrayList<String> result = new ArrayList<>();

        for (String word : words) {
            if (num.equals(changeNum(word, keys))) {
                result.add(word);
            }
        }

        return result;

    }

    public String changeNum(String word, Map<Character, String> keys) {
        char[] chars = word.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (char aChar : chars) {
            stringBuilder.append(keys.get(aChar));
        }
        return stringBuilder.toString();
    }

}
